package Priority_queue;

import javafx.util.Pair;

import java.util.*;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-03-06
 * Time:21:16
 * Text：692. 前K个高频单词
 */
public class Text2 {
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String,Integer> t1=new HashMap<>();
        for(String str:words){
            if(t1.getOrDefault(str,0)==0){
                t1.put(str,1);
            }else{
                t1.put(str,t1.get(str)+1);
            }
        }
        PriorityQueue<Pair<String,Integer>> pq=new PriorityQueue<>
                (
                        (a,b)->{
                            if(a.getValue().equals(b.getValue())){
                                return b.getKey().compareTo(a.getKey());
                            }
                            return a.getValue()-b.getValue();
                        }
                );
        for(Map.Entry<String,Integer> e:t1.entrySet()){
            pq.offer(new Pair<>(e.getKey(),e.getValue()));
            if(pq.size()>k){
                pq.poll();
            }
        }
        List<String> ret=new ArrayList<>();
        while(!pq.isEmpty()){
            ret.add(pq.poll().getKey());
        }
        Collections.reverse(ret);
        return ret;
    }
}
